/*
 * @copyright: Huang Ding
 * @Author: ding-cx
 * @Date: 2021-03-10 08:54:49
 * @LastEditors: ding-cx
 * @LastEditTime: 2021-04-06 15:06:50
 * @Description: file content
 */
import { Agent, WebSocketServer } from "egg";

import WsServer from "./WsServer";
export default (agent: Agent) => {
  // 实例化:
  // const wss = new WebSocketServer({ server }); //拿到egg吐出来的server实例（koa实例）给ws，实现共用同一个端口。
  let wss: WebSocketServer;
  try {
    // 默认使用7002端口作为ws服务。
    const options = Object.assign(
      { port: 7002 },
      agent.config?.ws?.wsOptions || {}
    );
    wss = new WsServer(options, undefined, agent);
    agent.coreLogger.info(
      "[egg-ws] websocket server init on agent. port : ",
      options.port
    );
    return wss;
  } catch (error) {
    agent.coreLogger.error("[egg-ws] new WebSocketServer error : ", error);
  }
};
